package org.xq.softcup.mq;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.xq.softcup.mq.model.XQRegistryDataParamVO;
import org.xq.softcup.mq.model.XQRegistryParamVO;
import org.xq.softcup.mq.util.BasicHttpUtil;
import org.xq.softcup.mq.util.BasicJson;

import java.util.*;

@Slf4j
public class XQRegistryBaseClient {
    private String adminAddress;
    private String accessToken;
    private String biz;
    private String env;
    private List<String> adminAddressArr;

    public XQRegistryBaseClient(String adminAddress, String accessToken, String biz, String env) {
        this.adminAddress = adminAddress;
        this.accessToken = accessToken;
        this.biz = biz;
        this.env = env;
        if (StringUtils.isEmpty(adminAddress)) {
            throw new RuntimeException("注册客户端 adminAddress为空");
        }
        if (StringUtils.isEmpty(biz)) {
            throw new RuntimeException("注册客户端 biz为空");
        }
        if (StringUtils.isEmpty(env)) {
            throw new RuntimeException("注册客户端 env为空");
        }
        this.adminAddressArr = new ArrayList();
        if (adminAddress.contains(",")) {
            this.adminAddressArr.addAll(Arrays.asList(adminAddress.split(",")));
        } else {
            this.adminAddressArr.add(adminAddress);
        }
    }

    /**
     * 客户端注册方法
     * @param registryDataList
     * @return
     */
    public boolean registry(List<XQRegistryDataParamVO> registryDataList) {
        if ((registryDataList == null) || (registryDataList.size() == 0)) {
            throw new RuntimeException("注册客户端 registryDataList为空");
        }
        for (XQRegistryDataParamVO registryParam : registryDataList) {
            if ((registryParam.getKey() == null) || (registryParam.getKey().trim().length() < 4) || (registryParam.getKey().trim().length() > 255)) {
                throw new RuntimeException("注册客户端 registryDataList Key无效");
            }
            if ((registryParam.getValue() == null) || (registryParam.getValue().trim().length() < 4) || (registryParam.getValue().trim().length() > 255)) {
                throw new RuntimeException("注册客户端 registryDataList 值无效");
            }
        }
        String pathUrl = "/api/registry"; //服务端接口
        XQRegistryParamVO registryParamVO = new XQRegistryParamVO();
        registryParamVO.setAccessToken(this.accessToken);
        registryParamVO.setBiz(this.biz);
        registryParamVO.setEnv(this.env);
        registryParamVO.setRegistryDataList(registryDataList);
        String paramsJson = BasicJson.toJson(registryParamVO);
        Map<String, Object> respObj = requestAndValid(pathUrl, paramsJson, 5);
        return respObj != null;
    }

    /**
     * 发送客户端的请求
     * @param pathUrl
     * @param requestBody
     * @param timeout
     * @return
     */
    private Map<String, Object> requestAndValid(String pathUrl, String requestBody, int timeout) {
        Iterator i$ = this.adminAddressArr.iterator();
        if (i$.hasNext()) {
            String adminAddressUrl = (String) i$.next();
            String finalUrl = adminAddressUrl + pathUrl;
            String responseData = BasicHttpUtil.postBody(finalUrl, requestBody, timeout);
            if (responseData == null) {
                return null;
            }
            Map<String, Object> resopnseMap = null;
            try {
                resopnseMap = BasicJson.parseMap(responseData);
            } catch (Exception localException) {
            }
            if ((resopnseMap == null) || (!resopnseMap.containsKey("code")) || (!"200".equals(String.valueOf(resopnseMap.get("code"))))) {
                log.warn("XQRegistryBaseClient 响应失败, responseData={}", responseData);
                return null;
            }
            return resopnseMap;
        }
        return null;
    }

    /**
     * 删除注册客户端
     *
     * @param registryDataList
     * @return
     */
    public boolean remove(List<XQRegistryDataParamVO> registryDataList) {
        if (registryDataList == null || registryDataList.size() == 0) {
            throw new RuntimeException("注册客户端 registryDataList为空");
        }
        for (XQRegistryDataParamVO registryParam : registryDataList) {
            if (registryParam.getKey() == null || registryParam.getKey().trim().length() == 0) {
                throw new RuntimeException("注册客户端 registryDataList Key无效");
            }
            if (registryParam.getValue() == null || registryParam.getValue().trim().length() == 0) {
                throw new RuntimeException("注册客户端 registryDataList 值无效");
            }
        }
        String pathUrl = "/api/remove"; //删除注册消费者
        XQRegistryParamVO registryParamVO = new XQRegistryParamVO();
        registryParamVO.setAccessToken(this.accessToken);
        registryParamVO.setBiz(this.biz);
        registryParamVO.setEnv(this.env);
        registryParamVO.setRegistryDataList(registryDataList);
        String paramsJson = BasicJson.toJson(registryParamVO);
        Map<String, Object> respObj = requestAndValid(pathUrl, paramsJson, 5);
        return respObj != null;
    }

    public Map<String, TreeSet<String>> discovery(Set<String> keys) {
        if ((keys == null) || (keys.size() == 0)) {
            throw new RuntimeException("注册客户端 keys 为空");
        }
        String pathUrl = "/api/discovery";
        XQRegistryParamVO registryParamVO = new XQRegistryParamVO();
        registryParamVO.setAccessToken(this.accessToken);
        registryParamVO.setBiz(this.biz);
        registryParamVO.setEnv(this.env);
        registryParamVO.setKeys(new ArrayList(keys));

        String paramsJson = BasicJson.toJson(registryParamVO);
        Map<String, Object> respObj = requestAndValid(pathUrl, paramsJson, 5);
        if ((respObj != null) && (respObj.containsKey("data"))) {
            Map<String, TreeSet<String>> data = (Map) respObj.get("data");
            return data;
        }
        return null;
    }

    public boolean monitor( Set<String> keys) {
        if ((keys == null) || (keys.size() == 0)) {
            throw new RuntimeException("注册客户端 keys 为空");
        }
        String pathUrl = "/api/monitor";
        XQRegistryParamVO registryParamVO = new XQRegistryParamVO();
        registryParamVO.setAccessToken(this.accessToken);
        registryParamVO.setBiz(this.biz);
        registryParamVO.setEnv(this.env);
        registryParamVO.setKeys(new ArrayList(keys));
        String paramsJson = BasicJson.toJson(registryParamVO);
        Map<String, Object> respObj = requestAndValid(pathUrl, paramsJson, 60);
        return respObj != null;
    }
}
